var debug = true;
$.extend({
	getIcon : function(type, title, clickable){
		var icon  = document.createElement('span');
		var className = 'ui-icon ' + type + ' ';
		if (clickable == undefined || clickable == true) {
			icon.style.cursor = 'pointer';
			className += ' clickable';
		}
		icon.className = className;
		icon.setAttribute('title', title);
		return icon;
	},

	cellElement : function(el){
		cell = document.createElement('td');
		cell.appendChild(el);
		return cell;
	},
	
	getUrlVars : function(){
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for (var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	},

  	getUrlVar : function(name){
		return $.getUrlVars()[name];
	},
	
	d : function(mixed) {
		if (debug == true) {
			console.log(mixed);
		}
	}
});

var uploadHelper = {
	init : function() {
		this.initUploadForm();
		this.initDragDrop();
	},
	
	initUploadForm : function() {
		var self = this;
		$('#files').bind('change', uploadHelper.uploadHandler);
		
		conf.upForm = $("#upload-form").dialog({
			autoOpen: false,
			height: 'auto',
			width: 500,
			modal: true,
			buttons: {
				"Select": function() {
					self.getContents();
				}
			}
		});
	},
	
	initDragDrop : function() {
		var self    = this;
		var dropbox = document.getElementById("application");
		
		dropbox.addEventListener("dragenter", this.dragOver, false);
		dropbox.addEventListener("dragover", this.dragOver, false);
		dropbox.addEventListener("dragleave", this.dragEnd, false);
		dropbox.addEventListener("drop", function(e) {
			self.dragEnd(e);
			conf.files = e.dataTransfer.files;
			self.getContents();
		}, false);
	},
	
	dragOver : function(e) {
		e.stopPropagation(); 
		e.preventDefault();
		$("#application").addClass('dragover');
	},
	
	dragEnd : function(e) {
		e.stopPropagation(); 
		e.preventDefault();
		$("#application").removeClass('dragover');
	},
	
	uploadHandler : function(e) {
		conf.files = e.target.files; // FileList object

	    // files is a FileList of File objects. List some properties.
	    var output = [];
	    for (var i = 0, f; f = conf.files[i]; i++) {
	      output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
	                  f.size, ' bytes, last modified: ',
	                  f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
	                  '</li>');
	    }
	    $('#list').html('<ul>' + output.join('') + '</ul>');
	},
	
	getContents : function() {
		conf.upForm.dialog('close');
		for (var i = 0; i < conf.files.length; i++) {
			var reader = new FileReader();
			reader.fileName = conf.files[i].name;
			if(reader.addEventListener) { 
				reader.addEventListener('loadend', this.readFile, false);
			// Chrome
			} else { 
				reader.onloadend = this.readFile;
			}
			reader.readAsText(conf.files[i]);
		}
	},
	
	readFile : function(e) {
		localStorage.setItem(tabHelper.getTabId(e.target.fileName), e.target.result);
		tabHelper.setTab(e.target.fileName);
	}
};

var tabHelper = {
	init: function() {
		
	},
		
	setTab : function(name) {
		var tabId   = this.getTabId(name);
		var tabName = name;
		conf.navi.tabs('add', '#' + tabId, tabName);
	},
	
	getTabId : function(fileName) {
		var pattern = new RegExp(fileName.replace('.', '-file-') + '.*');
		var id      = fileName.replace('.', '-file-') + '-' +
		$('.ui-tabs-panel').filter(function(){
			return this.id.match(pattern);
		}).size();
		 
		return id;
	}
};

var metricsHelper = {
	area: null,
	elements : {
		left : {
			el : null,
			cIndex : 0
		},
		top : {
			el : null,
			cIndex : 1
		},
		width : {
			el : null,
			cIndex : 2
		},
		height : {
			el : null,
			cIndex : 3
		}
	},
		
	init : function() {
		for (var element in metricsHelper.elements) {
			metricsHelper.elements[element].el = $('#prop-' + element)
				.on('keyup', {element : metricsHelper.elements[element]}, metricsHelper._update)
				.attr('disabled', true);
		}
		$.d(metricsHelper);
	},
	
	refreshMetrics : function(event) {
		metricsHelper.area = event.target;
		this._refreshElements();
	},
	
	reset : function() {
		metricsHelper.area = null;
		for (var element in metricsHelper.elements) {
			metricsHelper.elements[element].el.val('').attr('disabled', true);
		}
	},
	
	_refreshElements : function(coords) {
		$.d($(metricsHelper.area).area('option', 'area'));
		var coords = $(metricsHelper.area).area('option', 'area').attr('coords').split(',');
		for (var element in metricsHelper.elements) {
			metricsHelper.elements[element].el
				.val(coords[metricsHelper.elements[element].cIndex])
				.attr('disabled', false);
		}
	},
	
	_update : function(event) {
		var area   = $(metricsHelper.area).area('option', 'area');
		var coords = area.attr('coords').split(',');
		coords[event.data.element.cIndex] = event.data.element.el.val();
		area.attr('coords', coords.join(','));
		$(metricsHelper.area).area('refresh');
	}
};

var sourceHelper = {
		init : function() {
			conf.srcDlg = $("#source-dlg").dialog({
				draggable: true,
				autoOpen: false,
				height: 'auto',
				close: function() {
					$('.droppable').width('10%');
				},
				resizeStop: function(event, ui) {
					$('#src').height(ui.size.height - 50);
				}
			});
			//conf.srcDlg.dialog().parents('.ui-dialog').draggable( "option", "containment", '.toolbar' );
		},		
	};

var appHelper = {
	init: function() {
		conf.prop =  $('#properties').tabs();
    	
    	conf.navi = $('#application').tabs({
    		tabTemplate : "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
    		show: function(event, ui) {
				if (conf.mapped) {
					metricsHelper.reset();
					var tmpScroll = $('#app-tabs-container').scrollTop();
					$('#' + ui.panel.id).mapped('show');
					$('#app-tabs-container').scrollTop(tmpScroll);
				}
				$('#src').val($('#' + ui.panel.id).html());
			},
			add : function(event, ui) {
				$('#dropbox').hide();
				$(ui.panel)
					.append(localStorage.getItem(ui.panel.id))
					.appendTo($('#app-tabs-container'));
				appHelper.calibrate();
				$('#' + ui.panel.id).mapped({
					areaResizable: true,
			        areaDraggable: true,
			        container: 'parent',
					areaResize : function(e) {
						metricsHelper.refreshMetrics(e);
					},
					areaDrop : function(e) {
						metricsHelper.refreshMetrics(e);
					}
				});
				$(ui.tab).next().on('click', function() {
	        		var index = $('li', conf.navi).index($(this).parent());
	    			conf.navi.tabs('remove', index - conf.pageActions.length);
	    		});
			},
			remove : function(event, ui) {
				if (!$(this).tabs('length')) {
					$('#dropbox').show();
					appHelper.calibrate();
				}
			},
		}).resizable({
			handles: 's',
			helper: "ui-resizable-helper",
			stop : function(e, ui) {
				var newHeight = parseInt(ui.size.height / conf.frame.height() * 100);
				$(this).height(newHeight + '%');
				$('#properties').height((100 - newHeight) + '%');
				$(this).width('');
				appHelper.calibratePanels();
			}
		});
    	
    	var lang = $.getUrlVar('lang');
		if ($.inArray(lang, conf.availableLangs) == -1) {
			lang = conf.defaultLang;
		}
		i18n.lang = lang;
		
		conf.actions = $('#tabs-items').actions();
		conf.actions.actions('refresh', conf.pageActions);
		
		this.calibrate();
		$(window).bind('resize', this.calibrate);
	},

	calibrate : function() {
		conf.frame = $('.main-frame');
		conf.frame.height($(window).height() - 30);
		appHelper.calibratePanels();
	},
	
	calibratePanels : function() {
		$('.tabs-content').each(function(){
			if ($(this).children().length) {
				$(this).height($(this).parent().height() - 30);
				$('#src').height($(this).height() - 35);
			} else {
				$(this).height(0);
			}
		});
	}
};